# mkrules.mk -- global Makefile rules
# 
# Copyright(c) 2021 Cai_XL <Cai_XL@outlook.com>
# bilibili : https://space.bilibili.com/54910927
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# MKBOOTHEAD is defined in scripts/targets.mk

# some paramrters
SUB_TARGET ?=
SUB_SRC_PATH ?= 
SUB_LDS ?= 

# where to build sub-target
ifneq ($(SUB_TARGET),)
SUB_BUILD_DIR = $(BUILD_DIR)/$(SUB_TARGET)
SUB_TARGET_BIN = $(SUB_BUILD_DIR)/$(SUB_TARGET).bin
endif

# enum all source files and included paths
C_SRC = $(foreach dir,$(addsuffix /src,$(SUB_SRC_PATH)),$(wildcard $(dir)/*.c))
ASM_SRC = $(foreach dir,$(addsuffix /src,$(SUB_SRC_PATH)),$(wildcard $(dir)/*.s))
INC_PATH = $(addsuffix /inc,$(SUB_SRC_PATH))

# get all object files
OBJS = $(addprefix $(SUB_BUILD_DIR)/,$(notdir $(C_SRC:.c=.o)))
OBJS += $(addprefix $(SUB_BUILD_DIR)/,$(notdir $(ASM_SRC:.s=.o)))
vpath %.c $(addsuffix /src,$(SUB_SRC_PATH))
vpath %.s $(addsuffix /src,$(SUB_SRC_PATH))

# building rules
.PHONY:all
all:$(SUB_BUILD_DIR) $(SUB_TARGET_BIN)

# if SUB_BUILD_DIR not exists
$(SUB_BUILD_DIR):
	$(Q) echo making dir : $@
	$(Q) mkdir $@

# exporting *.bin from *.elf
$(SUB_TARGET_BIN):$(SUB_TARGET_BIN:.bin=.elf)
	$(Q)$(CROSS_BIN) $^ $@
	$(Q)$(MKBOOTHEAD) $@

# linking *.elf
$(SUB_TARGET_BIN:.bin=.elf):$(OBJS)
	$(Q)echo linking $@...
	$(Q)$(CROSS_CC) $^ $(LDFLAGS) -T$(SUB_LDS) -o $@
	$(Q)$(CROSS_SZ) $@
	$(Q)$(CROSS_DP) -D -S $@  > $(@:.elf=.txt)

$(SUB_BUILD_DIR)/%.o: %.c 
	$(Q)echo compling $<
	$(Q)$(CROSS_CC) -c $(CFLAGS) $(addprefix -I,$(INC_PATH)) $< -o $@

$(SUB_BUILD_DIR)/%.o:%.s
	$(Q)echo compling $<
	$(Q)$(CROSS_ASM) $(addprefix -I,$(INC_PATH)) -c $< -o $@